<template>
  <div id="app">
      <TodoHeader>
      <template #title>
        <h1 class="title">TodoList</h1>
      </template>
    </TodoHeader>
    <todo-input @add="addTodoItem"></todo-input>
    <todo-list :list="todos"></todo-list>
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader'
import TodoInput from './components/TodoInput'
import TodoList from './components/TodoList'

export default {
  name: 'App',
  components: {
    // 局部注册组件
    TodoHeader,
    TodoInput,
    TodoList
  },
  data: function() {
    return {
      todos: [
        {
          id: 1,
          title: '复习HTML',
          completed: true
        },
        {
          id: 2,
          title: '复习JavaScript',
          completed: false
        }
      ]
    }
  },
  // 组件实例被创建后执行 created 方法
  created() {
    console.log('app', this)
    // 绑定事件，接收待办事项的 id，删除数组中对应的待办事项
    this.$bus.$on('remove', this.removeTodoItem)
    // 绑定事件，接收待办事项的 id，修改数组中对应的待办事项状态
    this.$bus.$on('toggle', this.toggleTodoItem)
    // 获取网络接口中的待办事项数据
    fetch('https://jsonplaceholder.typicode.com/todos?userId=1')
      .then(res => res.json())
      .then(data => {
        this.todos = data
      })
  },
  methods: {
    // 添加新待办事项
    addTodoItem(title) {
      this.todos.push({
        id: Math.random(),
        title,
        completed: false
      })
    },
    // 修改待办事项完成状态
    toggleTodoItem(id) {
      this.todos.forEach(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed
        }
      })
    },
    // 删除待办事项
    removeTodoItem(id) {
      this.todos = this.todos.filter(todo => todo.id !== id)
    }
  },
  mixins: [
    {
      created() {
        console.log('局部 created 混入')
      }
    }
  ]
}
</script>

<style lang="scss">
</style>
